<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-7-26
 * Time: 下午4:35
 */

namespace console\controllers;

use common\components\ali\AppStore;
use common\components\proxy_payment\Fuiou;
use common\components\sms\Lhwt;
use common\components\tools\Bank;
use common\components\tools\Excel;
use common\components\tools\FileHelper;
use common\components\tools\Model;
use common\components\tools\Tools;
use common\models\AliCarinfoGetLog;
use common\models\BankBackSendLog;
use common\models\credit_app\ApiToken;
use common\models\credit_app\Order;
use common\models\credit_public\SlCarModel;
use common\models\credit_public\SlCarModelQczj;
use common\models\credit_public\SlCarModelSyc;
use common\models\credit_public\SlCarSeries;
use common\models\credit_public\SlCarSeriesSyc;
use common\models\Custom;
use common\models\FileListInfo;
use common\models\ManualPics;
use common\models\ManualPicsUploadQuene;
use common\models\MultiMedia;
use common\models\MultiMediaUploadQuene;
use console\models\db\TmpUploadMultiMedia;
use wodrow\yii\rest\ApiException;
use kartik\base\Config;
use common\components\tools\Api;
use common\models\credit_app\OrderCert;
use yii\base\ErrorException;
use yii\console\Controller;
use yii\db\Exception;
use yii\db\Expression;
use yii\httpclient\Client;

class JobController extends Controller
{
    /**
     * php yii job/test | php yii_dev job/test
     * 测试
     * @throws
     */
    public function actionTest()
    {
        $plat = new Fuiou();
        $plat->createPdfDocu();
    }

    /**
     * php yii job/index
     */
    public function actionIndex()
    {
        $token = "9tz6o1ouecwool5agutfDacHpo-qxlAp";
        $key = "hx5mbJ0W_5xJOxg6P8jkphRZUo_6hxU3";
        $timestamp = time();
//        $timestamp = "1541476413565";
        $nonce = $timestamp.rand(1000, 9999);
//        $nonce = "2320";
        $str = $token.$timestamp.$nonce.$key;
        var_dump($str);
        $sign = md5($token.$timestamp.$nonce.$key);
        var_dump($token);
        var_dump($timestamp);
        var_dump($nonce);
        var_dump($sign);
//        var_dump($key);
//        var_dump($token.$timestamp.$nonce.$key);
//        $timestamp = "1541411942554";
//        $nonce = "8.334342390048466";
//        var_dump($token.$timestamp.$nonce.$key);
//        var_dump(md5($token.$timestamp.$nonce.$key));
    }

    /**
     * 模拟接口提交征信
     * php yii job/batch-credit-by-app
     */
    public function actionBatchCreditByApp()
    {
        /**
         * @var OrderCert[] $order_certs
         */
//        $order_certs = OrderCert::find()->where(['between', 'ct_id', 135924, 136204])->all();
        $order_certs = OrderCert::find()->where(['ct_id' => 145139])->all();
        foreach ($order_certs as $k => $v) {
            if (!$v->ct_bigdata || 1) {
                $att = unserialize($v->ct_attach);
                $pics = [];
                /*foreach ($att as $k1 => $v1){
                    $pics['0001'] = isset($v1['fcard'])?$v1['fcard']:null;
                    $pics['0002'] = isset($v1['rcard'])?$v1['rcard']:null;
                    $pics['0003'] = isset($v1['auth'])?$v1['auth']:null;
                    $pics['0004'] = isset($v1['sign'])?$v1['sign']:null;
                }*/
                $pics['0001'] = isset($att['fcard']) ? "http://crm.app.qiche100.com" . $att['fcard'] : null;
                $pics['0002'] = isset($att['rcard']) ? "http://crm.app.qiche100.com" . $att['rcard'] : null;
                $pics['0003'] = isset($att['auth']) ? "http://crm.app.qiche100.com" . $att['auth'] : null;
                $pics['0004'] = isset($att['sign']) ? "http://crm.app.qiche100.com" . $att['sign'] : null;
                $uri = '/bank/business/submit-credit';
                $post_data = [
                    'guarantee_company_dot_site_sign_code' => 'yishang_dot_site_new_1',
                    'guarantee_company_user_id' => $v->order->o_id,
                    'orderno' => $v->order->o_number,
                    'master_name' => $v->ct_name,
                    'custom_name' => $v->order->o_vip_name,
                    'relation' => OrderCert::getKeyRelation()[$v->ct_key],
                    'idtype' => '000',
                    'idno' => $v->ct_code,
                    'pics' => serialize($pics),
                    'mobile' => $v->ct_mobile,
                    'bank_name' => $v->order->o_bank,
                    'bairong_validate' => 1,
                    'dont_send_to_bank_api' => 1,
                ];
                $resp = Api::request($uri, $post_data);
                $resp_arr = json_decode($resp->content, true, 512);
                $br_data = $resp_arr['data']['bairong_result'];
                $v->ct_bigdata_number = isset($br_data['swift_numbers']['detail_list']) ? $br_data['swift_numbers']['detail_list'] : null;
                $v->ct_bigdata_org = '百融金服';
                $v->ct_bigdata = $br_data['optimize_show'];
                $v->ct_bairong_result = json_encode($br_data, JSON_UNESCAPED_UNICODE);
                if (!$v->save()) {
                    var_dump($v->errors);
                }
            }
        }
    }

    /**
     * 模拟接口提交征信
     * php yii job/batch-credit-by-bank-back-log
     */
    public function actionBatchCreditByBankBackLog()
    {
        /**
         * @var BankBackSendLog[] $bblogs
         */
        $bblogs = BankBackSendLog::find()
            ->where(['request_route' => "Icbc/credit"])
            ->andWhere(['like', 'request_data', '"result":"099"'])
//            ->andWhere(['>', 'time', 1536130266])
            ->andWhere(['>', 'id', 49990])
            ->andWhere(['like', 'request_data', '图片下载失败，请检查后再提交'])->andWhere(['>', 'time', 1536130266])
//            ->andWhere(['not like', 'request_data', '韦小宝'])
//            ->andWhere(['not like', 'request_data', '杨福'])
            ->all();
        foreach ($bblogs as $k => $v) {
            $clog = $v->creditOrderLog;
            $app_post_data = unserialize($clog->app_post_data);
            $uri = DIRECTORY_SEPARATOR . $app_post_data['s'];
            $resp = Api::request($uri, $app_post_data);
            $resp_arr = json_decode($resp->content, true, 512);
            if ($resp_arr['code'] == '200') {
                var_dump($resp_arr);
            } else {
                var_dump($resp_arr);
                exit;
            }
        }
    }

    /**
     * php yii job/crawl-from-che300
     * 爬取che300数据
     * @throws Exception
     */
    public function actionCrawlFromChe300()
    {
        echo "stop";
        exit();
        $url = \common\components\che300\Config::$url_pre . "/getCarBrandList";
        $post_data = [
            'token' => \common\components\che300\Config::$token,
        ];
        $client = new Client();
        $c1 = clone $client;
        $sl_car_series = new SlCarSeries();
        $sl_car_model = new SlCarModel();
        $brands_resp = $c1->get($url, $post_data)->send();
        $brands = json_decode($brands_resp->content, true);
        SlCarSeries::deleteAll();
        SlCarModel::deleteAll();
        foreach ($brands['brand_list'] as $k => $v) {
            $c2 = clone $client;
            $series_resp = $c2->get(\common\components\che300\Config::$url_pre . "/getCarSeriesList", [
                'token' => \common\components\che300\Config::$token,
                'brandId' => $v['brand_id']
            ])->send();
            $series = json_decode($series_resp->content, true);
            foreach ($series['series_list'] as $k1 => $v1) {
                $trans = \Yii::$app->db_public->beginTransaction();
                try {
//                    if (!SlCarSeries::findOne(['cs_id' => $v1['series_id'], 'cs_car_brand' => $v['brand_name'], 'cs_car_text' => str_replace("-", "", $v1['series_group_name']) . "-" . str_replace("-", "", $v1['series_name']), 'cs_car_type' => $v1['maker_type'] == '进口'?'进口':'国产'])){
                    $sl_cs = clone $sl_car_series;
                    $sl_cs->cs_id = $v1['series_id'];
                    $sl_cs->cs_car_brand = $v['brand_name'];
                    $sl_cs->cs_car_text = str_replace("-", "", $v1['series_group_name']) . "-" . str_replace("-", "", $v1['series_name']);
                    $sl_cs->cs_car_type = $v1['maker_type'] == '进口' ? '进口' : '国产';
                    $sl_cs->cs_car_price1 = 0;
                    $sl_cs->cs_car_price2 = 0;
                    if (!$sl_cs->save()) {
                        var_dump($sl_cs->errors);
                        exit;
                    } else {
                        var_dump("save series");
                    }
//                    }
                    $c3 = clone $client;
                    $models_resp = $c3->get(\common\components\che300\Config::$url_pre . "/getCarModelList", [
                        'token' => \common\components\che300\Config::$token,
                        'seriesId' => $v1['series_id']
                    ])->send();
                    $models = json_decode($models_resp->content, true);
                    foreach ($models['model_list'] as $k2 => $v2) {
//                        if (!SlCarModel::findOne(['model_id' => $v2['model_id'], 'series_id' => $v1['series_id'], 'model_name' => $v2['model_name'], 'price' => $v2['model_price'], 'liter' => $v2['liter'], 'gear_type' => $v2['gear_type'], 'model_year' => $v2['model_year'], 'discharge_standard' => $v2['discharge_standard'], 'seat_number' => $v2['seat_number'], 'min_reg_year' => $v2['min_reg_year'], 'max_reg_year' => $v2['max_reg_year']])){
                        $sl_cm = clone $sl_car_model;
                        $sl_cm->model_id = $v2['model_id'];
                        $sl_cm->series_id = $v1['series_id'];
                        $sl_cm->model_name = $v2['model_name'];
                        $sl_cm->price = $v2['model_price'];
                        $sl_cm->liter = $v2['liter'];
                        $sl_cm->gear_type = $v2['gear_type'];
                        $sl_cm->model_year = $v2['model_year'];
                        $sl_cm->discharge_standard = $v2['discharge_standard'];
                        $sl_cm->seat_number = $v2['seat_number'];
                        $sl_cm->min_reg_year = $v2['min_reg_year'];
                        $sl_cm->max_reg_year = $v2['max_reg_year'];
                        if (!$sl_cm->save()) {
                            var_dump($sl_cm->errors);
                            exit;
                        } else {
                            var_dump("save model");
                        }
//                        }
                    }
                    $trans->commit();
                    var_dump("ok");
                } catch (Exception $e) {
                    $trans->rollBack();
                    throw $e;
                }
            }
        }
    }

    /**
     * php yii job/crawl-add-che300-syc
     * 爬取che300数据 test 1.0.36 standard 1.0.486
     * @throws Exception
     */
    public function actionCrawlAddChe300Syc($version = '')
    {
        exit;
        $url = \common\components\che300\Config::$url_pre . "/common/eval";
        $params = [
            'token' => \common\components\che300\Config::$token,
            'oper' => "exportCommercialModel",
        ];
//        $_url = $url."?oper=exportCommercialModel&token=".\common\components\che300\Config::$token;
//        var_dump($_url);exit;
        if ($version)$params['fromVersion'] = $version;
        $key = 'cac300s--' . $version;
//        \Yii::$app->cache->delete($key);
        $content = \Yii::$app->cache->get($key);
        if (!$content) {
            $client = new Client();
            $resp = $client->get($url, $params)->send();
            $content = $resp->content;
            \Yii::$app->cache->set($key, $content, 3600);
        }
        $arr = json_decode($content, true);
        $status = $arr['status'];
        if ($status) {
            $data = $arr['data'];
            $sl_car_series = new SlCarSeriesSyc();
            $sl_car_model = new SlCarModelSyc();
            foreach ($data['series'] as $k => $v) {
                $sl_cs = SlCarSeriesSyc::findOne(['cs_id' => $v['series_id']]);
                if (!$sl_cs){
                    $sl_cs = clone $sl_car_series;
                    $sl_cs->cs_id = $v['series_id'];
                }
                $sl_cs->cs_car_brand = $v['brand_name'];
//                $sl_cs->cs_car_text = str_replace("-", "", $v['series_group_name']) . "-" . str_replace("-", "", $v['series_name']);
                $sl_cs->cs_car_text = $v['brand_name'] . "-" . $v['series_name'];
//                $sl_cs->cs_car_type = $v['maker_type'] == '进口' ? '进口' : '国产';
                $sl_cs->cs_car_price1 = 0;
                $sl_cs->cs_car_price2 = 0;
                if (!$sl_cs->save()) {
                    var_dump($sl_cs->errors);
                    exit;
                } else {
                    var_dump("save series:{$v['series_id']}");
                }
            }
            foreach ($data['model'] as $k => $v){
                $sl_cm = SlCarModelSyc::findOne(['model_id' => $v['model_id']]);
                if (!$sl_cm){
                    $sl_cm = clone $sl_car_model;
                    $sl_cm->model_id = $v['model_id'];
                }
                $sl_cm->series_id = $v['series_id'];
                $sl_cm->model_name = $v['model_name'];
                $sl_cm->price = $v['price'];
                if (isset($v['liter']))$sl_cm->liter = (string)$v['liter'];
                if (isset($v['gear_type']))$sl_cm->gear_type = $v['gear_type'];
                $sl_cm->model_year = (string)$v['model_year'];
                if (isset($v['discharge_standard']))$sl_cm->discharge_standard = $v['discharge_standard'];
                if (isset($v['seat_number']))$sl_cm->seat_number = $v['seat_number'];
                if (isset($v['min_reg_year']))$sl_cm->min_reg_year = $v['min_reg_year'];
                if (isset($v['max_reg_year']))$sl_cm->max_reg_year = $v['max_reg_year'];
                if (!$sl_cm->save()) {
                    var_dump($sl_cm->errors);
                    exit;
                } else {
                    var_dump("save model:{$v['model_id']}");
                }
            }
            var_dump($data['version']);
        } else {
            $error_msg = $arr['error_msg'];
            var_dump($error_msg);
        }
    }

    /**
     * php yii job/crawl-add-from-che300
     * 增量爬取che300数据
     * @throws Exception
     */
    public function actionCrawlAddFromChe300($version = '')
    {
        $url = \common\components\che300\Config::$url_pre . "/common/eval";
        $params = [
            'oper' => "exportModel",
            'token' => \common\components\che300\Config::$token,
        ];
        if ($version)$params['fromVersion'] = $version;
//        $_url = $url."?oper=exportModel&token=".\common\components\che300\Config::$token;
//        var_dump($_url);exit;
        $key = 'cafc300--' . $version;
        \Yii::$app->cache->delete($key);
        $content = \Yii::$app->cache->get($key);
        if (!$content) {
            $client = new Client();
            $resp = $client->get($url, $params)->send();
            $content = $resp->content;
            \Yii::$app->cache->set($key, $content, 3600);
        }
        $arr = json_decode($content, true);
        $status = $arr['status'];
        if ($status) {
            $data = $arr['data'];
//            var_dump($data['brand'][0]);
//            var_dump($data['series'][0]);
//            var_dump($data['model'][0]);
//            exit;
            $sl_car_series = new SlCarSeries();
            $sl_car_model = new SlCarModel();
            foreach ($data['series'] as $k => $v) {
//                if ($v['oper_type']=="更新"){
//                    $sl_cs = SlCarSeries::findOne(['cs_id' => $v['series_id']]);
//                }
                $sl_cs = SlCarSeries::findOne(['cs_id' => $v['series_id']]);
                if (!$sl_cs){
                    $sl_cs = clone $sl_car_series;
                    $sl_cs->cs_id = $v['series_id'];
                }
                $sl_cs->cs_car_brand = $v['brand_name'];
                $sl_cs->cs_car_text = str_replace("-", "", $v['series_group_name']) . "-" . str_replace("-", "", $v['series_name']);
                $sl_cs->cs_car_type = $v['maker_type'] == '进口' ? '进口' : '国产';
                $sl_cs->cs_car_price1 = 0;
                $sl_cs->cs_car_price2 = 0;
                if (!$sl_cs->save()) {
                    var_dump($sl_cs->errors);
                    exit;
                } else {
                    var_dump("save series:{$v['series_id']}");
                }
            }
            foreach ($data['model'] as $k => $v){
//                if ($v['oper_type']=="更新"){
//                    $sl_cm = SlCarModel::findOne(['model_id' => $v['model_id']]);
//                }
                $sl_cm = SlCarModel::findOne(['model_id' => $v['model_id']]);
                if (!$sl_cm){
                    $sl_cm = clone $sl_car_model;
                    $sl_cm->model_id = $v['model_id'];
                }
                $sl_cm->series_id = $v['series_id'];
                $sl_cm->model_name = $v['model_name'];
                $sl_cm->price = $v['price'];
                $sl_cm->liter = $v['liter'];
                $sl_cm->gear_type = $v['gear_type'];
                $sl_cm->model_year = $v['model_year'];
                $sl_cm->discharge_standard = $v['discharge_standard'];
                $sl_cm->seat_number = $v['seat_number'];
                $sl_cm->min_reg_year = $v['min_reg_year'];
                $sl_cm->max_reg_year = $v['max_reg_year'];
                if (!$sl_cm->save()) {
                    var_dump($sl_cm->errors);
                    exit;
                } else {
                    var_dump("save model:{$v['model_id']}");
                }
            }
            var_dump($data['version']);
        } else {
            $error_msg = $arr['error_msg'];
            var_dump($error_msg);
        }
    }

    /**
     * php yii job/pack-icbc-files
     * 打包icbc数据
     */
    public function actionPackIcbcFiles()
    {
        /**
         * @var OrderCert[] $order_certs
         */
        $order_certs = OrderCert::find()->where(['between', 'ct_id', 97369, 140564])->all();
        foreach ($order_certs as $k => $v) {
            $order = $v->order;
            if ($order->o_bank == '（2017）中国工商银行股份有限公司杭州延中支行') {
                $b = true;
                $add_t = $order->o_add_time;
                $month = date("m", $add_t);
                $attachs = unserialize($v->ct_attach);
                $tmp_dir = \Yii::getAlias("@runtime/tmp");
                $pack_dir = $tmp_dir . DIRECTORY_SEPARATOR . $month;
                if (!is_dir($pack_dir)) {
                    \yii\helpers\FileHelper::createDirectory($pack_dir, '0777');
                }
                $vcode = $v->ct_code;
                $code_end4 = substr($vcode, -4);
                $user_dir = $pack_dir . DIRECTORY_SEPARATOR . $v->ct_name . $code_end4;
                if (!is_dir($user_dir)) {
                    \yii\helpers\FileHelper::createDirectory($user_dir, '0777');
                }
                $filename = "身份证正面照" . "." . FileHelper::getExtensionName1($attachs['fcard']);
                $file_path = $user_dir . DIRECTORY_SEPARATOR . $filename;
                $b = $b && file_put_contents($file_path, file_get_contents("http://crm.app.qiche100.com" . $attachs['fcard']));

                $filename = "身份证反面照" . "." . FileHelper::getExtensionName1($attachs['rcard']);
                $file_path = $user_dir . DIRECTORY_SEPARATOR . $filename;
                $b = $b && file_put_contents($file_path, file_get_contents("http://crm.app.qiche100.com" . $attachs['rcard']));
                $filename = "授权书" . "." . FileHelper::getExtensionName1($attachs['auth']);
                $file_path = $user_dir . DIRECTORY_SEPARATOR . $filename;
                $b = $b && file_put_contents($file_path, file_get_contents("http://crm.app.qiche100.com" . $attachs['auth']));
                $filename = "签字照" . "." . FileHelper::getExtensionName1($attachs['sign']);
                $file_path = $user_dir . DIRECTORY_SEPARATOR . $filename;
                $b = $b && file_put_contents($file_path, file_get_contents("http://crm.app.qiche100.com" . $attachs['sign']));
                if ($b) {
                    var_dump("success");
                } else {
                    var_dump("false");
                }
            }
        }
    }

    /**
     * php yii job/delete-do-quene-lock
     * 删除异步处理手工图片上传锁
     */
    public function actionDeleteDoQueneLock()
    {
        $lock_key = "DoQueneManualPics";
        $x = \Yii::$app->cache->delete($lock_key);
        var_dump($x);
    }

    /**
     * 初始化所有手工获取图片任务队列
     * php yii job/set-all-do-quene-ready
     */
    public function actionSetAllDoQueneReady()
    {
        exit;
        $lock_key = "DoQueneManualPics";
        $lock_id = \Yii::$app->cache->get($lock_key);
        if ($lock_id == ManualPicsUploadQuene::STATUS_DOING) {
            var_dump("job is doing");
            exit;
        }
        $x = ManualPicsUploadQuene::updateAll(['status' => ManualPicsUploadQuene::STATUS_READY]);
        var_dump($x);
    }

    /**
     * 异步处理手工图片上传
     * php yii job/do-quene-manual-pics
     * @throws ErrorException
     * @throws Exception
     * @throws \yii\base\Exception
     */
    public function actionDoQueneManualPics()
    {
        $lock_key = "DoQueneManualPics";
        $lock_id = \Yii::$app->cache->get($lock_key);
        if ($lock_id == ManualPicsUploadQuene::STATUS_DOING) {
            var_dump("job is doing");
            exit;
        }
        if (ManualPicsUploadQuene::findOne(['status' => ManualPicsUploadQuene::STATUS_DOING])){
            var_dump("job locked");
            exit;
        }
        \Yii::$app->cache->set($lock_key, ManualPicsUploadQuene::STATUS_DOING, 86400);
        $quenes = ManualPicsUploadQuene::find()->where(['status' => ManualPicsUploadQuene::STATUS_READY])->all();
        foreach ($quenes as $k => $v) {
            $v->status = ManualPicsUploadQuene::STATUS_DOING;
            if (!$v->save()) {
                throw new Exception("ManualPicsUploadQuene save error:" . Model::getModelError($v));
            } else {
                var_dump("ManualPicsUploadQuene doing: " . $v->id);
            }
            $pics = json_decode($v->pics, true);
            $manual_pics = \common\components\tools\Bank::UploadIcbcPicsCommon($v->dirname, $pics);
            ManualPics::deleteAll(['custom_id' => $v->custom_id]);
            $model = new ManualPics();
            foreach ($manual_pics as $k1 => $v1) {
                if (isset($v1['picurl']) && $v1['picurl']) {
//                    if (!ManualPics::findOne(['custom_id' => $v->custom_id, 'picid' => $v1['picid'], 'picurl' => $v1['picurl']])){}
                    $_m_pic = clone $model;
                    $_m_pic->custom_id = $v->custom_id;
                    $_m_pic->picid = $v1['picid'];
                    $_m_pic->picurl = $v1['picurl'];
                    $_m_pic->created_at = time();
                    $_m_pic->picnote = isset($v1['picnote']) ? $v1['picnote'] : null;
                    if (!$_m_pic->save()) {
                        throw new Exception("ManualPics save error:" . Model::getModelError($_m_pic));
                    } else {
                        var_dump($_m_pic->picurl);
                    }
                }
            }
            $v->status = ManualPicsUploadQuene::STATUS_DONE;
            if (!$v->save()) {
                throw new Exception("ManualPicsUploadQuene save error:" . Model::getModelError($v));
            } else {
                var_dump("ManualPicsUploadQuene save success " . $v->id);
            }
        }
        \Yii::$app->cache->set($lock_key, ManualPicsUploadQuene::STATUS_DONE, 86400);
    }

    /**
     * php yii job/delete-multi-media-quene-lock
     * 删除异步处理多媒体文件上传锁
     */
    public function actionDeleteMultiMediaQueneLock()
    {
        $lock_key = "MultiMediaQuene1";
      	var_dump(\Yii::$app->cache->get($lock_key));
        $x = \Yii::$app->cache->delete($lock_key);
      	var_dump($x);
      	var_dump(\Yii::$app->cache->get($lock_key));
    }

    /**
     * 异步处理多媒体文件上传
     * php yii job/do-quene-multi-media
     * @throws ErrorException
     * @throws Exception
     * @throws \yii\base\Exception
     */
    public function actionDoQueneMultiMedia()
    {
        $lock_key = "MultiMediaQuene1";
        $lock_id = \Yii::$app->cache->get($lock_key);
        if ($lock_id == MultiMediaUploadQuene::STATUS_DOING) {
            var_dump("job is doing");
            exit;
        }
        if (MultiMediaUploadQuene::findOne(['status' => ManualPicsUploadQuene::STATUS_DOING])){
            var_dump("job locked");
            exit;
        }
        \Yii::$app->cache->set($lock_key, MultiMediaUploadQuene::STATUS_DOING, 86400*30);
        $quenes = MultiMediaUploadQuene::find()->where(['status' => ManualPicsUploadQuene::STATUS_READY])->all();
        foreach ($quenes as $k => $v) {
            $v->status = MultiMediaUploadQuene::STATUS_DOING;
            if (!$v->save()) {
                throw new Exception("MultiMediaUploadQuene save error:" . Model::getModelError($v));
            } else {
                var_dump("MultiMediaUploadQuene doing: " . $v->id);
            }
            $urls = json_decode($v->file_urls, true);
            try{
                $_urls = \common\components\tools\Bank::uploadMultiMedia($v->dirname, $urls, $v->custom_id);
                if (!is_array($_urls)){
                    if ($_urls){
                        if (MultiMediaUploadQuene::STATUS_FILE_LARGE_30M == $_urls){
                            $v->status = $_urls;
                            $v->save();
                        }
                    }
                    var_dump($_urls);
                    continue;
                }
            }catch (Exception $e){
                $v->status = MultiMediaUploadQuene::STATUS_FILE_UPLOAD_FAILED;
                $v->save();
                continue;
            }
            /*if (!isset($v->custom->lastCreditOrder->bankGuaranteeCompanyBind)){
//                throw new \yii\console\Exception("绑定银行不是合作银行");
                $v->status = 5;
                $v->save();
                continue;
            }*/
            var_dump($_urls);
            $resp = Api::request('/bank/business/supply-general-service-multimedia', [
                'orderno' => $v->custom->orderno,
                'pics' => serialize($_urls),
                'idno' => $v->idno,
            ]);
            $resp_arr = json_decode($resp->content, true);
            if ($resp_arr['code']!=200){
                var_dump($resp_arr);exit;
            }
            if (!isset($resp_arr['data']['send_return_msg'])){
                var_dump($resp->content);exit;
            }else{
                if ($resp_arr['data']['send_return_msg'] != 'success'){
                    var_dump($resp_arr['send_return_msg']);exit;
                }
            }
//            MultiMedia::deleteAll(['custom_id' => $v->custom_id]);
            $model = new MultiMedia();
            foreach ($_urls as $k1 => $v1) {
                if (isset($v1['picurl']) && $v1['picurl']) {
//                    if (!ManualPics::findOne(['custom_id' => $v->custom_id, 'picid' => $v1['picid'], 'picurl' => $v1['picurl']])){}
                    if (!MultiMedia::findOne(['picurl' => $v1['picurl']])){
                        $_m = clone $model;
                        $_m->custom_id = $v->custom_id;
                        $_m->picid = $v1['picid'];
                        $_m->picurl = $v1['picurl'];
                        $_m->created_at = time();
                        $_m->picnote = isset($v1['picnote']) ? $v1['picnote'] : null;
                        if (!$_m->save()) {
                            throw new Exception("MultiMedia save error:" . Model::getModelError($_m));
                        } else {
                            var_dump($_m->picurl);
                        }
                    }
                }
            }
            $v->status = MultiMediaUploadQuene::STATUS_DONE;
            if (!$v->save()) {
                throw new Exception("MultiMediaUploadQuene save error:" . Model::getModelError($v));
            } else {
                var_dump("MultiMediaUploadQuene save success " . $v->id);
            }
        }
        \Yii::$app->cache->set($lock_key, MultiMediaUploadQuene::STATUS_DONE, 86400*30);
    }

    /**
     * 异步处理多媒体文件上传
     * php yii job/do-quene-multi-media-tmp
     * @throws ErrorException
     * @throws Exception
     * @throws \yii\base\Exception
     */
    public function actionDoQueneMultiMediaTmp()
    {
        $quenes = MultiMediaUploadQuene::find()->where(['status' => 2])->all();
        foreach ($quenes as $k => $v) {
            $_urls = [
                [
                    'picid' => '8888',
                    'picurl' => \Yii::$app->params['pic_url_type'].str_replace('/', '_', \Yii::getAlias("@uploads_url/medias/{$v->dirname}")."/{$v->custom_id}".".zip"),
                ],
            ];
            var_dump($_urls);
            $resp = Api::request('/bank/business/supply-general-service-multimedia', [
                'orderno' => $v->custom->orderno,
                'pics' => serialize($_urls),
                'idno' => $v->idno,
            ]);
            $resp_arr = json_decode($resp->content, true);
            if ($resp_arr['code']!=200){
//                var_dump($resp_arr);exit;
                $v->status = 3;
                $v->save();
                continue;
            }
            if (!isset($resp_arr['data']['send_return_msg'])){
                $v->status = 4;
                $v->save();
                continue;
            }else{
                if ($resp_arr['data']['send_return_msg'] != 'success'){
                    $v->status = 5;
                    $v->save();
                    continue;
                }
            }
            $model = MultiMedia::find()->where(['custom_id' => $v->custom_id])->one();
            if (!$model){
                throw new \yii\base\Exception("没有找到MultiMedia");
            }
            $model->last_visit_at = 0;
            $model->save();
            $v->status = MultiMediaUploadQuene::STATUS_DONE;
            if (!$v->save()) {
                throw new Exception("MultiMediaUploadQuene save error:" . Model::getModelError($v));
            } else {
                var_dump("MultiMediaUploadQuene save success " . $v->id);
            }
        }
    }

    /**
     * php yii job/tmp-media-upload
     * 处理临时多媒体文件上传
     */
    public function actionTmpMediaUpload()
    {
        $_a = \common\models\TmpUploadMultiMedia::find()->where(['status' => \common\models\TmpUploadMultiMedia::STATUS_READY])->limit(1000)->all();
        $q = new MultiMediaUploadQuene();
        foreach ($_a as $k => $v){
            $sql = <<<SQL
SELECT orderno FROM credit_order_log
LEFT JOIN credit_order ON credit_order.id = credit_order_id
LEFT JOIN bank ON bank_id = bank.id
LEFT JOIN custom ON custom_id = custom.id
WHERE idno='{$v->idcard}' -- 作为参数
AND bank.`name` = '中国工商银行股份有限公司杭州延中支行' -- 作为参数
AND api_return_code = '00000'
ORDER BY field(relation, '本人', '配偶', '反担保', '担保人'), credit_order_log.time desc
LIMIT 0,1
SQL;
            $a1 = \Yii::$app->db->createCommand($sql)->queryOne();
            $custom = Custom::findOne(['orderno' => $a1['orderno']]);
          	if($custom===null){
              	$v->status = 2;
              	$v->save();
              	continue;
            }
            $quene = MultiMediaUploadQuene::findOne(['custom_id' => $custom->id]);
            if (!$quene){
                $quene = clone $q;
                $quene->custom_id = $custom->id;
            }else{
                if ($quene->status == 1){
                    throw new ApiException(201903061137, "订单正在进行中，请稍后");
                }
            }
            $urls = Tools::str2arr($v->url);
            $file_urls = [];
            foreach ($urls as $k1 => $v1){
                $file_urls[] = ['picid' => '8888', 'picurl' => $v1];
            }
            $quene->file_urls = json_encode($file_urls);
            $quene->dirname = Bank::DIR_MULTI_MEDIA;
            $quene->status = MultiMediaUploadQuene::STATUS_READY;
            $quene->created_at = time();
            $quene->idno = $v->idcard;
            if (!$quene->save()){
                throw new Exception(\common\components\tools\Model::getModelError($quene));
            }
            $v->status = \common\models\TmpUploadMultiMedia::STATUS_DONE;
            $v->o_fcustid = $quene->custom_id;
            if (!$v->save()){
                throw new Exception(\common\components\tools\Model::getModelError($v));
            }
            var_dump($quene->toArray());
        }
    }

    /**
     * php yii job/lsfpzw-do
     * 乐税发票真伪队列处理
     */
    public function actionLsfpzwDo()
    {
        $models = AliCarinfoGetLog::find()->where(['in', 'invoicefalseCode', ['202', '216']])->andWhere(['type' => AliCarinfoGetLog::TYPE_LSFPZW])->all();
        foreach ($models as $k => $v){
            $x = $v->request_file_url;
            $y = Tools::str2arr($x, " ");
            $v->fphm = $y[1];
            $v->fpdm = $y[0];
            $v->kprq = $y[2];
            $v->jshe = $y[3];
            $resp = Api::request('/chedai/ali/invoice-info-for-com', [
                'o_id' => $v->o_id,
                'iifc_type' => AppStore::invoiceInfoForCom_TYPE_2,
                'invoiceCode' => $v->fpdm,
                'invoiceNumber' => $v->fphm,
                'billTime' => $v->kprq,
                'checkCode' => null,
                'invoiceAmount' => $v->jshe,
                'uid' => $v->uid,
            ]);
            $body = $resp->content;
            $v->status = AliCarinfoGetLog::STATUS_DEFAULT;
            $v->save();
            echo $body;
        }
    }

    /**
     * php yii job/lsfpzw-error-do
     * 乐税发票真伪队列处理
     */
    public function actionLsfpzwErrorDo()
    {
        $models = AliCarinfoGetLog::find()->where(['type' => AliCarinfoGetLog::TYPE_LSFPZW])->andWhere(['in', 'invoicefalseCode', ["213", '218']])->andWhere(['<', 'console_check_times', 5])->limit(10)->all();
        var_dump(count($models));
        foreach ($models as $k => $v){
            var_dump($v->id);
            $x = $v->request_file_url;
            $y = Tools::str2arr($x, " ");
            $v->fphm = $y[1];
            $v->fpdm = $y[0];
            $v->kprq = $y[2];
            $v->jshe = $y[3];
            $resp = Api::request('/chedai/ali/invoice-info-for-com', [
                'o_id' => $v->o_id,
                'iifc_type' => AppStore::invoiceInfoForCom_TYPE_2,
                'invoiceCode' => $v->fpdm,
                'invoiceNumber' => $v->fphm,
                'billTime' => $v->kprq,
                'checkCode' => null,
                'invoiceAmount' => $v->jshe,
                'uid' => $v->uid,
            ]);
            $body = $resp->content;
            /*$arr = json_decode($body, true);
            $v->resultMsg = $arr['resultMsg'];
            $v->invoiceName = $arr['invoiceName'];
            $v->invoicefalseCode = $arr['invoicefalseCode'];
            $v->isFree = $arr['isFree'];
            $v->RtnCode = $arr['RtnCode'];
            $v->resultCode = $arr['resultCode'];
            $v->invoiceResult = $arr['invoiceResult'];
            $v->resp_body = $body;*/
            $v->console_check_times ++;
            $v->status = AliCarinfoGetLog::STATUS_DEFAULT;
            $v->save();
            echo $body;
            echo "\n";
        }
    }

    /**
     * php yii job/force-all-app-user-login
     * 强制所有app用户登录
     * @return int
     */
    public function actionForceAllAppUserLogin()
    {
        return ApiToken::updateAll(['tk_expiration' => 0]);
    }

    /**
     * php yii job/map-car-ys-che300
     */
    public function actionMapCarYsChe300()
    {}

    /**
     * php yii job/busi-car-crawler-by-che300
     */
    public function actionBusiCarCrawlerByChe300()
    {
        $client = new Client();
        $resp = $client->get(\common\components\che300\Config::$url_pre, [
            'oper' => "getCommercialCarBrandList",
            'token' => \common\components\che300\Config::$token,
        ])->send();
        $r = json_decode($resp->content, true);
        var_dump($r);exit;
    }

    /**
     * edivide订单作废
     * php yii job/edivi-zf
     */
    public function actionEdiviZf()
    {
        $orders = Order::find()->where(['IS', 'o_estage_orderno', new Expression('NOT NULL')])->andWhere(['o_status' => "征信提交"])->andWhere(['<', 'o_add_time', time()-86400*2])->all();
        foreach ($orders as $k => $order){
            $x = OrderCert::find()->where(['ct_oid' => $order->o_id])->andWhere(['!=', 'ct_electron_tag', 0])->count();
            if ($x == 0){
                foreach ($order->certs as $k1 => $cert) {
                    if ($cert->ct_electron_tag == 0){
                        $json = <<<JSON
{"orderNo":"{$order->o_id}","applyType":"2","applyReason":"过期批量作废","applyName":"控制台"}
JSON;
                        $resp = Api::request('/e_divide/default/order-apply', ['json' => $json]);
                        Tools::log($order->o_id, 'edivi-zf');
                        Tools::log($resp->content, 'edivi-zf');
                        $order->o_status = "作废";
                        $cert->ct_status = "del";
                        $order->save(false);
                        $cert->save(false);
                        var_dump(1);
                        continue;
                    }else{
                        var_dump(0);
                    }
                }
            }else{
                var_dump($order->o_id);
            }
        }
    }
}